import Taro, { Component, Config } from '@tarojs/taro';
import { ComponentClass } from 'react'

import { View, Input } from '@tarojs/components'
import './index.less'
import { extend } from '../../utils/public'

const timeItemWidth = 90; //默认时间组的宽度
type PageOwnProps = {
  children?: any;
}

type PageState = {
  show: boolean;  //控制显示隐藏
  res: boolean | null; //判断点击了哪一个按钮
  objectParms: objectParms;  //show方法的参数
  animationData: any; //动画
  timeArray: string[]; //时间类型的时间数组
  shaplineWidth: number; //时间类型中上方线条的宽度
  selectedIndex: number;
  activeshapWidth: number;
  passwordArray: string[];
  isFocus: boolean;
}
type Iprops = PageOwnProps;

interface objectParms {
  title: string;
  mintitle: string;
  content: any;
  success: Function;
  cancaleBtnText?: string;
  submitBtnText?: string;
  haveButton?: boolean;
  modalCtxType?: string;
}

enum ModelType {
  T1 = 'text',
  T2 = 'timing',
  T3 = 'passwordverify'
}

interface Modal {
  props: Iprops;
  state: PageState;
}

class Modal extends Component {
  config: Config = {

  }
  constructor(props) {
    super(props);
    this.state = {
      show: false,
      res: null,
      objectParms: {
        title: '',
        mintitle: '',
        content: '',
        success: () => { },
        cancaleBtnText: '取消',
        submitBtnText: '确定',
        haveButton: true,
        modalCtxType: 'text',
      },
      shaplineWidth: 430,
      activeshapWidth: 0,
      selectedIndex: 0,
      animationData: {},
      timeArray: ['5分钟', '10分钟', '15分钟', '20分钟', '25分钟','30分钟'],
      passwordArray: ['','','',''],
      isFocus: true
    }
  }

  static defaultProps = {

  }

  animation: any;

  componentWillMount() {
    let { timeArray }: PageState = this.state;
    if(timeArray.length > 0 ) {
      let width: number = timeItemWidth * (timeArray.length -1) - 10;
      this.setState({
        shaplineWidth: width,
      })
    }
  }

  componentWillUpdate(nextProps, nextState) {
    // if (nextState.show) {
    //   Taro.hideTabBar({
    //     animation: true
    //   });
    // } else {
    //   Taro.showTabBar({
    //     animation: true
    //   });
    // }
  }
  //组件Pro是否完成更新
  componentDidUpdate(prevProps, prevState) {

  }

  //渲染组件
  render() {
    let { timeArray }: PageState = this.state;
    return (
      <View>
        {
          this.state.show && <View className="container-modal">
            <View animation={this.state.animationData} className={this.state.show ? 'modal-info-container active' : 'modal-info-container'}>
              <View className="modal-info-top">
                <View className="modal-info-title">
                  {this.state.objectParms.title}
                  <View className="modal-info-mintitle">
                    {this.state.objectParms.mintitle}
                  </View>
                </View>
                <View className="modal-info-content">
                  {this.state.objectParms.content}
                  {this.state.objectParms.modalCtxType == ModelType.T2
                    ? <View className="op-container">
                      <View className="shape-line" style={{ width: this.state.shaplineWidth + 'rpx'}}></View>
                      <View className="activeshap-contianer" style={{ width: this.state.shaplineWidth + 'rpx' }}>
                        <View className="activeshap-line" style={{ width: this.state.activeshapWidth + 'rpx' }}></View>
                      </View>
                        <View className="op-shap-container">
                            {timeArray.map((item, index) => {
                              return (
                                <View className="time-item" data-index={index} onClick={this.selectTiming} key={index}>
                                  <View className={this.state.selectedIndex >= index ? 'shape-circle active' : 'shape-circle'}></View>
                                  <View className={ this.state.selectedIndex >= index ? 'time-text active': 'time-text '}>
                                    {item}
                                  </View>
                                </View>
                              )
                            })}
                        </View>
                    </View>
                    : ''
                  }
                  { this.state.objectParms.modalCtxType == ModelType.T3
                    ? <View className="pasdword-container">
                        <View className="box-input">
                          {
                          this.state.passwordArray.map((item,index) => {
                              return (
                                <View className={item !== '' ? 'password-item active' : 'password-item'} key={index} onClick={this.onInputFocus}>
                                  {item}
                                </View>
                              )
                            })
                          }
                        </View>
                      <Input className="password-input" selectionStart={-8} selectionEnd={-10} cursor={-4} type="number" focus={this.state.isFocus } onInput={this.getInputText} onBlur={this.InputOnblur}/>
                        <View className="">
                          忘记安全密码
                        </View>

                      </View>
                    : ''
                  }
                </View>
              </View>
              <View className="modal-info-bottom">
                {
                  this.state.objectParms.haveButton && <View className="modal-info-button">
                    <View className="modal-btn-cancel" onClick={this.clickCancel}>{this.state.objectParms.cancaleBtnText}</View>
                    <View className="modal-btn-sure" onClick={this.clickSubmitBtn}>{this.state.objectParms.submitBtnText}</View>
                  </View>
                }
              </View>
            </View>
          </View>
        }
      </View>
    )
  }

  show = (obj: objectParms): void => {
    let newobj = this.state.objectParms;
    extend(newobj, obj)
    this.setState({
      show: true,
      objectParms: newobj
    })
    let animation = Taro.createAnimation({
      duration: 300,
      timingFunction: "ease",
      delay: 0
    })
    this.animation = animation;
    this.animation.opacity(0).step()
    this.setState({
      animationData: this.animation.export()
    })
    setTimeout(function () {
      this.animation.opacity(1).translateY(-45).step()
      this.setState({
        animationData: this.animation.export()
      })
    }.bind(this), 500)
  }
  //
  hide
  //执行成功的函数
  success(cb: any) {
    cb();
  }
  //点击取消按钮
  clickCancel() {
    this.clickButton('cancel');
  }
  //点击确定按钮
  clickSubmitBtn(): void {
    this.clickButton('confirm');
    Taro.scanCode({

    }).then(res=> {
      console.log(res);
    })
  }
  //选择启动时长
  selectTiming(e):void {
    let index: number = e.currentTarget.dataset.index;
    this.setState({
      selectedIndex: index,
      activeshapWidth: index * 90
    })
  }

  getInputText(e) {
    let inputText: string = e.detail.value;
    let inputTextArray: string[] = inputText.split('');
    let num: number = inputTextArray.length - this.state.passwordArray.length;
    if (inputText.length>= 4) {
      let res = {
        inputDone: true
      }
      this.success(() => {
        if (this.state.objectParms['success']) {
          this.state.objectParms['success'](res);
        }
      })
    }
    if (num < 0) {
      num = this.state.passwordArray.length - inputTextArray.length;
      for (let i = 0; i < num;i++ ) {
        inputTextArray.push('');
      }
    } else if (num > 0 ) {
      inputTextArray = inputTextArray.slice(0, this.state.passwordArray.length)
    }
    this.setState({
      passwordArray: inputTextArray
    });
  }
  //聚焦
  onInputFocus(): void {
    this.setState({
      isFocus: true
    })
  }
  //失去焦点
  InputOnblur(): void {
    this.setState({
      isFocus: false
    })
  }
  //复制属性
  extend(newobj: objectParms, oldobj: objectParms):void {
    for (let i in oldobj) {
      newobj[i] = oldobj[i];
    }
  }

  //点击按钮
  clickButton (type: string) {
    let { objectParms } = this.state;
    let res = {
      confirm: false,
      cancel: false
    }
    if(type == 'confirm') {
      res.confirm = true;
    } else if (type == 'cancel' ) {
      res.cancel = true;
    }
    this.success(() => {
      if (this.state.objectParms['success']) {
        this.state.objectParms['success'](res);
      }
    })
    objectParms.content = '';
    objectParms.modalCtxType = 'text';
    objectParms.cancaleBtnText = '取消';
    objectParms.submitBtnText = '确定';
    objectParms.title = '';
    objectParms.mintitle = '';
    objectParms.success = ()=> {};
    objectParms.haveButton = true;
      this.setState({
        res: true,
        show: false,
        objectParms: objectParms
      })
  }
}

export default Modal as ComponentClass<PageOwnProps, PageState>